import { INestApplication, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

import { API_SECURITY_AUTH } from './common/decorators/swagger.decorator';
import { ConfigKeyPaths, IAppConfig, ISwaggerConfig } from './config';

export function setupSwagger(
  app: INestApplication,
  configService: ConfigService<ConfigKeyPaths>,
) {
  const { name, globalPrefix } = configService.get<IAppConfig>('app')!;
  const { enable, path, serverUrl } =
    configService.get<ISwaggerConfig>('swagger')!;

  if (!enable) return;

  const swaggerPath = `${serverUrl}/${path}`;

  const documentBuilder = new DocumentBuilder()
    .setTitle(name)
    .setDescription(
      `
🔷 **Base URL**: \`${serverUrl}/${globalPrefix}\` <br>
🧾 **Swagger JSON**: [查看文档 JSON - 可下载导入apifox](${swaggerPath}/json)
    `,
    )
    .setVersion('1.0')
    .addServer(`${serverUrl}/${globalPrefix}`, 'Base URL');

  // auth security
  documentBuilder.addSecurity(API_SECURITY_AUTH, {
    description: '输入令牌（Enter the token）',
    type: 'http',
    scheme: 'bearer',
    bearerFormat: 'JWT',
  });

  const document = SwaggerModule.createDocument(app, documentBuilder.build(), {
    ignoreGlobalPrefix: true,
  });

  SwaggerModule.setup(path, app, document, {
    swaggerOptions: {
      persistAuthorization: true, // 保持登录
    },
    jsonDocumentUrl: `/${path}/json`,
  });

  return () => {
    // started log
    const logger = new Logger('SwaggerModule');
    logger.log(`Swagger UI: ${swaggerPath}`);
    logger.log(`Swagger JSON: ${swaggerPath}/json`);
  };
}
